using System.Collections.Generic;
using System.Linq;
using Toast.Core;
using Toast.Extensions;
using Toast.Core.Interfaces;

namespace Toast.Filters
{
    public class PositionalInjectionDictionary : Dictionary<InjectAt, string>
    {
        public PositionalInjectionDictionary(IEnumerable<IContent> contentCollection, string packageKey)
        {
            foreach (var script in contentCollection.Where(x => x.InjectAt == InjectAt.Default))
                script.InjectAt = ToastCore.DefaultInjectAt;

            foreach (var injectPostGroup in contentCollection.GroupBy(x => x.InjectAt))
            {
                var result = string.Empty;

                foreach (var scriptTypeGroup in injectPostGroup.GroupBy(x => x.GetType()))
                {
                    var formatter = scriptTypeGroup.First().GetFormatter(packageKey);
                    result += ToastCore.SeperateFiles
                                  ? scriptTypeGroup.Select(x => formatter.Format(x, true)).Join("\r\n")
                                  : formatter.Format(scriptTypeGroup, false);
                }

                Add(injectPostGroup.Key, result);
            }
        }

    }
}